<template>
  <div class="contract-home">
    <div class="header">
      <h1>合同管理</h1>
    </div>
    
    <!-- 修改为居中布局的容器 -->
    <div class="centered-container">
      <!-- 左侧正方形申请按钮 -->
      <div class="left-square" @click="goToApply">
        <div class="square-content">
          <el-icon :size="60" color="#409EFF"><Plus /></el-icon>
          <h3>申请新合同</h3>
          <p>点击此处开始新的合同申请流程</p>
        </div>
      </div>
      
   <!-- 右侧长方形合同列表 -->
      <div class="right-container">
        <div class="applied-contracts">
          <h3 class="applied-title">我已申请的合同</h3>
          <el-divider />
          
          <div class="applied-list">
            <el-empty description="暂无合同申请记录" v-if="contractList.length === 0" />
            
            <div class="contract-item" v-for="contract in contractList" :key="contract.id">
              <div class="contract-info">
                <h4 class="contract-name">{{ contract.title || contract.name }}</h4>
                <div class="contract-meta">
                  <el-tag :type="getStatusTagType(contract.status)" size="small">
                    {{ contract.status }}
                  </el-tag>
                  <span class="contract-number">{{ contract.number }}</span>
                </div>
                <div class="contract-date">
                  <span>申请日期: {{ contract.applyDate }}</span>
                </div>
              </div>
              <el-button 
                type="text" 
                size="small" 
                @click="onViewContract(contract)"
              >
                查看详情
              </el-button>
               <el-button 
               type="text" 
               size="small" 
               @click="onEditContract(contract)"
               >
                编辑
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 合同详情对话框 -->
    <el-dialog 
      v-model="showDetailDialog" 
      :title="`合同详情 - ${currentContract?.number || ''}`" 
      width="60%"
    >
      <div v-if="currentContract" class="contract-detail">
        <div class="detail-row">
          <span class="label">合同名称：</span>
          <span class="value">{{ currentContract.title }}</span>
        </div>
        <div class="detail-row">
          <span class="label">企业名称：</span>
          <span class="value">{{ currentContract.name }}</span>
        </div>
        <div class="detail-row">
          <span class="label">合同类型：</span>
          <span class="value">{{ currentContract.type }}</span>
        </div>
        <div class="detail-row">
          <span class="label">生效日期：</span>
          <span class="value">{{ currentContract.date }}</span>
        </div>
        <div class="detail-row">
          <span class="label">到期日期：</span>
          <span class="value">{{ currentContract.contractEndDate }}</span>
        </div>
        <div class="detail-row">
          <span class="label">申请日期：</span>
          <span class="value">{{ currentContract.applyDate }}</span>
        </div>
        <div class="detail-row">
          <span class="label">当前状态：</span>
          <el-tag :type="getStatusTagType(currentContract.status)">
            {{ currentContract.status }}
          </el-tag>
        </div>
        <div class="detail-row" v-if="currentContract.rejectReason">
          <span class="label">拒绝原因：</span>
          <span class="value">{{ currentContract.rejectReason }}</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="exportContract(currentContract)"
          v-if="currentContract?.status === '已通过'"
        >
          导出合同
        </el-button>
      </template>
    </el-dialog>
  </div>

     <!-- 合同详情组件 -->
    <ContractShow ref="contractShowRef" />
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useContractStore } from '@/stores/contractStore'
import ContractShow from './component/ContractShow.vue'

const router = useRouter()
const contractStore = useContractStore()

// 数据状态
const loading = ref(false)
const showDetailDialog = ref(false)
const currentContract = ref(null)
const contractShowRef = ref(null) // 引用合同详情组件

// 查看合同详情
const onViewContract = (contract) => {
  console.log('查看合同详情:', contract) // 调试用
  contractShowRef.value.open(contract) // 调用子组件方法打开对话框
}

const onEditContract = (contract) => {
  console.log('编辑合同:', contract)
  // 这里可以跳转到编辑页面，或者打开编辑对话框
  router.push({
    path: '/contractapply',
    query: { 
       id: contract.id,
       editMode: true 
     }
  })
}

// 从store获取合同列表
const contractList = computed(() => {
  // 合并已生效合同和待审批合同
  return [...contractStore.contracts, ...contractStore.pendingApprovals]
    // 按申请日期降序排序
    .sort((a, b) => new Date(b.applyDate) - new Date(a.applyDate))
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case '已通过': return 'success'
    case '待审批': return 'warning'
    case '已拒绝': return 'danger'
    default: return ''
  }
}

// 跳转到申请页面
const goToApply = () => {
  router.push('/contractapply')
}

// 查看合同详情
const viewContractDetail = (contract) => {
  currentContract.value = contract
  showDetailDialog.value = true
}

// 导出合同
const exportContract = (contract) => {
  ElMessage.success(`开始导出合同 ${contract.number}`)
  // 这里可以添加实际的导出逻辑
  showDetailDialog.value = false
}

// 刷新合同列表
const refreshList = async () => {
  try {
    loading.value = true
    // 模拟从store获取数据
    contractList.value = [
      ...contractStore.contracts,
      ...contractStore.pendingApprovals
    ].filter(c => c.applicant === '当前用户') // 假设只显示当前用户申请的合同
    
    ElMessage.success('合同列表已刷新')
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  refreshList()
})
</script>

<style scoped>
.contract-home {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

/* 新增的居中容器样式 */
.centered-container {
  display: flex;
  justify-content: center;
  gap: 40px;
  max-width: 1200px;
  margin: 0 auto;
}

.left-square {
  width: 300px;
  height: 300px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.left-square:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.square-content {
  text-align: center;
  padding: 20px;
}

.square-content h3 {
  margin: 15px 0 10px;
  font-size: 18px;
  color: #333;
}

.square-content p {
  color: #999;
  font-size: 14px;
}

/* 右侧容器样式 */
.right-container {
  width: 380px;
  height: 360px;
}

.applied-contracts {
  background-color: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.applied-title {
  font-size: 20px;
  color: #333;
  margin: 0 0 15px 0;
}

.applied-list {
  min-height: 300px;
  max-height: 70vh;
  overflow-y: auto;
}

.contract-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.contract-info {
  flex: 1;
  margin-right: 15px;
}

.contract-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.contract-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.contract-number {
  font-size: 13px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.contract-date {
  font-size: 12px;
  color: #999;
  display: flex;
  flex-direction: column;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .centered-container {
    flex-direction: column;
    align-items: center;
  }
  
  .right-container {
    width: 100%;
    max-width: 600px;
    margin-top: 40px;
  }
  
  .left-square {
    width: 100%;
    max-width: 400px;
  }
}

@media (max-width: 768px) {
  .applied-title {
    font-size: 18px;
  }
  
  .contract-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .contract-info {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
}
.contract-actions {
  display: flex;
  gap: 8px;
}
</style>